import { Translation, TranslationInfo, TranslationModule } from '../types/translation';

/**
 * 引用信息接口
 */
export interface ReferenceInfo {
  // 引用的翻译键ID
  targetId: string;
  // 原始模块ID
  sourceModuleId: string;
  // 引用计数
  count: number;
}

/**
 * 模块引用处理服务
 * 用于识别和处理翻译键的跨模块引用
 */
export class ModuleReferenceHandler {
  // 翻译键索引，用于快速查找
  private keyIndex: Map<string, {
    info: TranslationInfo;
    moduleId: string;
    frequency: number;
  }> = new Map();
  
  // 引用映射，记录每个模块中的引用信息
  private referenceMap: Map<string, ReferenceInfo[]> = new Map();
  
  /**
   * 处理模块树中的引用关系
   * @param rootModule 根模块
   * @returns 包含处理后的根模块和引用统计
   */
  public processReferences(rootModule: Translation): {
    rootModule: Translation;
    statistics: {
      totalReferences: number;
      keyWithMostReferences: string;
      maxReferenceCount: number;
    };
  } {
    // 第一步：构建翻译键索引
    this.buildKeyIndex(rootModule);
    
    // 第二步：识别重复的翻译键
    this.identifyDuplicateKeys();
    
    // 第三步：构建引用关系
    this.buildReferences();
    
    // 第四步：将引用信息添加到模块中
    this.injectReferencesToModules(rootModule);
    
    // 统计信息
    const statistics = this.generateReferenceStatistics();
    
    return {
      rootModule,
      statistics
    };
  }
  
  /**
   * 构建翻译键索引
   * @param module 当前处理的模块
   * @param currentPath 当前路径，用于构建模块ID
   */
  private buildKeyIndex(module: Translation, currentPath: string = ''): void {
    const modulePath = currentPath ? `${currentPath}.${module.id}` : module.id;
    
    // 处理子模块和翻译键
    for (const subModule of module.subModules) {
      if (!subModule.isKey) {
        // 递归处理子模块
        this.buildKeyIndex(subModule as Translation, modulePath);
      } else {
        // 处理翻译键
        const translationInfo = subModule as TranslationInfo;
        const key = translationInfo.key;
        
        // 添加到索引
        this.keyIndex.set(key, {
          info: translationInfo,
          moduleId: module.id,
          frequency: translationInfo.frequency
        });
      }
    }
  }
  
  /**
   * 识别重复的翻译键
   */
  private identifyDuplicateKeys(): void {
    // 按键名分组
    const keyGroups = new Map<string, Array<{
      info: TranslationInfo;
      moduleId: string;
      frequency: number;
    }>>();
    
    // 将索引中的键按名称分组
    for (const [key, entry] of this.keyIndex.entries()) {
      if (!keyGroups.has(key)) {
        keyGroups.set(key, []);
      }
      
      keyGroups.get(key)!.push(entry);
    }
    
    // 处理每个有多个条目的组
    for (const [key, entries] of keyGroups.entries()) {
      if (entries.length <= 1) continue;
      
      // 按使用频率排序，找出主要归属模块
      entries.sort((a, b) => b.frequency - a.frequency);
      
      const primaryEntry = entries[0];
      
      // 为其他条目创建引用
      for (let i = 1; i < entries.length; i++) {
        const entry = entries[i];
        
        // 添加引用信息
        const referenceInfo: ReferenceInfo = {
          targetId: primaryEntry.info.id,
          sourceModuleId: entry.moduleId,
          count: entry.frequency
        };
        
        // 将引用添加到映射中
        if (!this.referenceMap.has(entry.moduleId)) {
          this.referenceMap.set(entry.moduleId, []);
        }
        
        this.referenceMap.get(entry.moduleId)!.push(referenceInfo);
      }
    }
  }
  
  /**
   * 构建引用关系
   */
  private buildReferences(): void {
    // 已在identifyDuplicateKeys中实现
  }
  
  /**
   * 将引用信息注入到模块中
   * @param module 当前处理的模块
   */
  private injectReferencesToModules(module: Translation): void {
    // 检查当前模块是否有引用
    if (this.referenceMap.has(module.id)) {
      const references = this.referenceMap.get(module.id)!;
      
      // 添加引用属性
      (module as any).references = references;
    }
    
    // 递归处理子模块
    for (const subModule of module.subModules) {
      if (!subModule.isKey) {
        this.injectReferencesToModules(subModule as Translation);
      }
    }
  }
  
  /**
   * 生成引用统计信息
   */
  private generateReferenceStatistics(): {
    totalReferences: number;
    keyWithMostReferences: string;
    maxReferenceCount: number;
  } {
    let totalReferences = 0;
    let keyWithMostReferences = '';
    let maxReferenceCount = 0;
    
    // 计算引用的键和计数
    const referenceCounts = new Map<string, number>();
    
    // 统计每个键被引用的次数
    for (const references of this.referenceMap.values()) {
      for (const ref of references) {
        totalReferences++;
        
        if (!referenceCounts.has(ref.targetId)) {
          referenceCounts.set(ref.targetId, 0);
        }
        
        const newCount = referenceCounts.get(ref.targetId)! + ref.count;
        referenceCounts.set(ref.targetId, newCount);
        
        if (newCount > maxReferenceCount) {
          maxReferenceCount = newCount;
          keyWithMostReferences = ref.targetId;
        }
      }
    }
    
    return {
      totalReferences,
      keyWithMostReferences,
      maxReferenceCount
    };
  }
} 